package com.findMe.service.impl;

import com.findMe.entity.User;
import com.findMe.exception.UserException;
import com.findMe.mapper.UserMapper;
import com.findMe.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service("UserService")
public class UserServiceImpl implements UserService {

    @Autowired
    @Qualifier("UserMapper")
    private UserMapper userMapper;

    @Override
    /**
     * 判断是否存在，与添加进数据库，否则抛出异常
     */
    public User regist(User user) throws UserException {
        User byUsername = userMapper.findByUsername(user.getUsername());
        if (byUsername != null)
            throw new UserException("用户名已经存在");

        userMapper.addUser(user);
        byUsername = userMapper.findByUsername(user.getUsername());
        return byUsername;
    }

    @Override
    public User login(User user) throws UserException {
        User byUsername = userMapper.findByUsername(user.getUsername());
        if (byUsername == null)
            throw new UserException("用户名错误");

        User verifyUser = userMapper.verifyUser(user);
        if (verifyUser == null)
            throw new UserException("密码错误");

        return verifyUser;
    }
}
